package prisd.brand.com.threegangswitch.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Arrays;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import prisd.brand.com.threegangswitch.R;
import prisd.brand.com.threegangswitch.pojo.LampBean;
import prisd.brand.com.threegangswitch.util.HexUtil;
import prisd.brand.com.threegangswitch.util.InputUtils;
import prisd.brand.com.threegangswitch.util.NetworkUtil;

import static prisd.brand.com.threegangswitch.util.WiFiUtil.intToIp;

public class MainActivity extends AppCompatActivity {


    @BindView(R.id.btn_1)
    Button btn1;
    @BindView(R.id.btn_2)
    Button btn2;
    @BindView(R.id.btn_3)
    Button btn3;
    @BindView(R.id.btn_4)
    Button btn4;
    @BindView(R.id.btn_5)
    Button btn5;
    @BindView(R.id.btn_6)
    Button btn6;
    @BindView(R.id.pb)
    ProgressBar pb;
    private String strIp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initView();

    }

    public static String method1(String val) {
        try {
            SecretKeySpec localSecretKeySpec = new SecretKeySpec("13ed457a49931224dc6dc20fd71ac7f4".getBytes("UTF-8"), 0, "13ed457a49931224dc6dc20fd71ac7f4".getBytes("UTF-8").length, "AES");

            Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            byte[] encoded = localSecretKeySpec.getEncoded();
            Logger.i("localSecretKeySpec: "+ Arrays.toString(encoded)+ " "+encoded);
            localCipher.init(1, localSecretKeySpec);
            return Base64.encodeToString(localCipher.doFinal(val.getBytes("UTF-8")), 0).replaceAll("\r|\n", "");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private String method2(String val) {
        try {
            SecretKeySpec localSecretKeySpec = new SecretKeySpec("13ed457a49931224dc6dc20fd71ac7f4".getBytes("UTF-8"), 0, "13ed457a49931224dc6dc20fd71ac7f4".getBytes("UTF-8").length, "AES");
            Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            localCipher.init(2, localSecretKeySpec);//Base64.DEFAULT
            byte[] decode = Base64.decode(val, 0);
            byte[] bytes = localCipher.doFinal(decode);
            String result = new String(bytes, "UTF-8");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void initView() {

    }


    private Handler h = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    break;
            }
            return false;
        }
    });

    @OnClick({R.id.btn_1, R.id.btn_2, R.id.btn_3, R.id.btn_4, R.id.btn_5, R.id.btn_6})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_1:
                Boolean wifiConnected = isWifiConnected();
                break;
            case R.id.btn_2:
                ConnectDisplay();
                connectToDevice();
                break;
            case R.id.btn_3:
                break;
            case R.id.btn_4:
                break;
            case R.id.btn_5:
                break;
            case R.id.btn_6:
                sendCommand(new LampBean(), true);
                break;
        }
    }

    private Boolean isWifiConnected() {
        boolean wifiConnected = NetworkUtil.isWifiConnected(this);
        if (wifiConnected) {
            Toast.makeText(this, "已连接wifi", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "请连接wifi", Toast.LENGTH_SHORT).show();
        }
        return wifiConnected;
    }

    private void searchDevice() {

    }

    /**
     * 手机接入模块的WIFI网络
     */
    private void ConnectDisplay() {
//        //扫描WIFI
//        WiFiUtil.startScan();
        WifiManager wifiManger = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        DhcpInfo dhcpInfo = wifiManger.getDhcpInfo();
        int ip = dhcpInfo.serverAddress;
        //此处获取ip为整数类型，需要进行转换
        strIp = intToIp(ip);
        Logger.d(strIp);

    }

    private void ConfigurationParameters(String ssid, String psw) {

    }

    public static final String STHEME_LAMP_DPID_1 = "1"; //灯开关

    private void sendCommand(LampBean bean, boolean var) {
        try {
            bean.setOpen(var);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put(STHEME_LAMP_DPID_1, bean.isOpen());
            Gson gson = new Gson();
            String json = gson.toJson(hashMap);
            Logger.i(json);
            byte[] bytes = json.getBytes();
            InetAddress address = InetAddress.getByName(strIp);
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
            datagramPacket.setAddress(address);
            datagramPacket.setPort(5000);
            DatagramSocket socket = new DatagramSocket();
            socket.send(datagramPacket);
            Logger.i("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final String HOST = "182.168.4.1";
    private static final int PORT = 8888;

    public void sendData(String host, int port, byte[] data) {
        try {
            DatagramSocket clientSocket = new DatagramSocket();
            InetSocketAddress serverAddress = new InetSocketAddress(host, port);
            DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress);
            clientSocket.send(packet);
            clientSocket.close();
            Logger.d("--->端口：" + port + " \n DATA:" + HexUtil.bytesToHexString(data));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void connectToDevice() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Socket socket = new Socket(strIp, 5000);
                    if (socket.isConnected()) {
                        Logger.i("连接成功");
                    } else {
                        Logger.e("连接失败");
                    }

                    ExecutorService pool = Executors.newFixedThreadPool(2);
                    pool.execute(new chatIn(socket));
                    pool.execute(new chatOut(socket));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    static class chatIn implements Runnable {

        private Socket socket;

        public chatIn(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while (true) {
                    String s = br.readLine();

                    if (s == null) {
                        break;
                    }
                    System.out.println("服务端说:" + s);
                }
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    static class chatOut implements Runnable {
        private Socket socket;

        public chatOut(Socket socket) {
            this.socket = socket;
        }

        @TargetApi(Build.VERSION_CODES.KITKAT)
        @Override
        public void run() {

            try (OutputStream os = socket.getOutputStream();
                 PrintWriter p = new PrintWriter(new OutputStreamWriter(os), true)) {
                while (true) {
                    String input = InputUtils.Input("请输入想发送的信息:");
                    p.println(input);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
